package com.eastseeway.radioproject.main;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.eastseeway.radioproject.base.BaseViewModel;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.entities.BaseResponse;
import com.eastseeway.radioproject.entities.BeanDeviceInfo;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import struct.StructException;

public class MainViewModel extends BaseViewModel<MainRepository> {

    private final MutableLiveData<Boolean> isDeviceEnabled = new MutableLiveData<>(false);

    private final MutableLiveData<DeviceStatus> deviceStatusMutableLiveData = new MutableLiveData<>();
//    private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
    private final MutableLiveData<String> infoContent = new MutableLiveData<>();
    private DeviceStatus deviceStatus ;
    private final Handler handler = new Handler();

    public MainViewModel(@NonNull Application application) {
        super(application);
        deviceStatus = new DeviceStatus(true, false, false);
        getDeviceStatusMutableLiveData().setValue(deviceStatus);
        handler.postDelayed(checkPressureHandleTimeout, 3000);
        handler.postDelayed(checkNPressureHandleTimeout, 3000);
    }
    private final Runnable checkPressureHandleTimeout = () -> {
        deviceStatus.setDetectingHandles(false);
        deviceStatus.setPressureHandleOnline(false);
        getDeviceStatusMutableLiveData().setValue(deviceStatus);
    };
    private final Runnable checkNPressureHandleTimeout = () -> {
        deviceStatus.setDetectingHandles(false);
        deviceStatus.setNPressureHandleOnline(false);
        getDeviceStatusMutableLiveData().setValue(deviceStatus);
    };

    public void processDataFrame(int deviceAddress) {
        if (deviceAddress == Const.ADDRESS_FROM_HANDLE_1_DATA_1) {
            handler.removeCallbacks(checkPressureHandleTimeout);
            deviceStatus.setDetectingHandles(false);
            deviceStatus.setPressureHandleOnline(true);
            getDeviceStatusMutableLiveData().setValue(deviceStatus);
            handler.postDelayed(checkPressureHandleTimeout, 3000);
        } else if (deviceAddress == Const.ADDRESS_FROM_HANDLE_2_DATA_1) {
            handler.removeCallbacks(checkNPressureHandleTimeout);
            deviceStatus.setDetectingHandles(false);
            deviceStatus.setNPressureHandleOnline(true);
            getDeviceStatusMutableLiveData().setValue(deviceStatus);
            handler.postDelayed(checkNPressureHandleTimeout, 3000);
        }
    }


    @Override
    protected void onCleared() {
        super.onCleared();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected MainRepository setRepository() {
        return new MainRepository();
    }

    void getDeviceInfo(){
        if (!isNetConnected()) {
            return;
        }
        if (isDeviceIdInvalid()) {
            return;
        }
        mRepository.getDeviceInfo(SPHelper.getDeviceId(getApplication()), new Callback<BaseResponse<BeanDeviceInfo>>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<BeanDeviceInfo>> call, @NonNull Response<BaseResponse<BeanDeviceInfo>> response) {
                if (response.body().isSuccess()) {
                    BeanDeviceInfo result = response.body().getResult();
                    SPHelper.saveDeviceInfo(getApplication(), result);
                    isDeviceEnabled.setValue(result.getDeviceEnabled().equals("N"));
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<BeanDeviceInfo>> call, @NonNull Throwable throwable) {

            }
        });
    }

    void sendHandleMessageToSwitchBoard(byte msg){
        try {
            byte[] bytes = CommandGenerator.commandToSwitchBoard(Const.ADDRESS_TO_SWITCH_BOARD, msg, msg, msg);
            sendMessage(bytes);
        } catch (StructException e) {
            throw new RuntimeException(e);
        }
    }

    public MutableLiveData<DeviceStatus> getDeviceStatusMutableLiveData() {
        return deviceStatusMutableLiveData;
    }


    public MutableLiveData<String> getInfoContent() {
        return infoContent;
    }

}
